package com.ccb.sc.common.modules.common.service.impl;

import com.aliyun.oss.OSSClient;
import com.aliyun.oss.common.utils.BinaryUtil;
import com.aliyun.oss.model.MatchMode;
import com.aliyun.oss.model.PolicyConditions;
import com.ccb.sc.common.conf.OssProperties;
import com.ccb.sc.common.modules.common.service.IAliyunOssService;
import com.ccb.sc.common.modules.common.vo.AliyunOssStsVo;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import java.nio.charset.StandardCharsets;
import java.util.Date;

/**
 * <p>
 * 序列号服务
 * </p>
 * @author ken
 * @version 1.0
 * @date 2020-09-15
 */
@Service
public class AliyunOssServiceImpl implements IAliyunOssService {

    private static final Logger logger = LoggerFactory.getLogger(IAliyunOssService.class);

    private OssProperties ossProperties;
    private OSSClient client;

    @Override
    public AliyunOssStsVo getAliyunSts(String dir) {
        AliyunOssStsVo ossStsVo = new AliyunOssStsVo();
        // host的格式为 bucketname.endpoint
        String host = "https://" + ossProperties.getBucket() + "." + ossProperties.getEndpoint();
        try {
            long expireTime = 5 * 60;
            long expireEndTime = System.currentTimeMillis() + expireTime * 1000;
            Date expiration = new Date(expireEndTime);
            PolicyConditions policyConds = new PolicyConditions();
            policyConds.addConditionItem(PolicyConditions.COND_CONTENT_LENGTH_RANGE, 0, 1048576000);
            policyConds.addConditionItem(MatchMode.StartWith, PolicyConditions.COND_KEY, dir);

            String postPolicy = client.generatePostPolicy(expiration, policyConds);
            byte[] binaryData = postPolicy.getBytes(StandardCharsets.UTF_8);
            String encodedPolicy = BinaryUtil.toBase64String(binaryData);
            String postSignature = client.calculatePostSignature(postPolicy);

            ossStsVo.setAccessId(client.getCredentialsProvider().getCredentials().getAccessKeyId());
            ossStsVo.setDir(dir);
            ossStsVo.setExpire(String.valueOf(expireEndTime / 1000));
            ossStsVo.setHost(host);
            ossStsVo.setPolicy(encodedPolicy);
            ossStsVo.setSignature(postSignature);
        } catch (Exception e) {
            e.printStackTrace();
            logger.error("get aliyun oss sts error!");
        }
        return ossStsVo;
    }

    @Autowired
    public void setOssProperties(OssProperties ossProperties) {
        this.ossProperties = ossProperties;
    }

    @Autowired
    public void setClient(OSSClient client) {
        this.client = client;
    }
}
